<script>
import axios from "axios";
import {getBaseUrl} from "@/js/common.js";

export default {
  name: "LoginDialog",
  data(){
    return {
      dialogVisible: false,
      form: {
        userName: '',
        password: ''
      },
      rules: {
        userName: [
          {validator: this.checkUserName, trigger: 'blur'}
        ],
        password: [
          {validator: this.checkPassword, trigger: 'blur'}
        ]
      },
      loginError: ''
    }
  },
  methods: {
    onSubmit() {
      this.$refs.loginForm.validate((valid) => {
        if (!valid) return
        axios.post(getBaseUrl('userCenter') + '/user/login', this.form).then(res => {
          if (res.data.code === 500){
            this.loginError = res.data.msg
            this.$refs.loginForm.validate(() => {
              this.loginError = ''
            })
          }else if (res.data.code === 200){
            this.$message.success('登录成功')
            sessionStorage.setItem('massToken', res.data.data)
            window.location.reload()
          }
        })
      })
    },
    checkUserName(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入用户名'));
      } else if (this.loginError === '账号不存在'){
        callback(new Error('账号不存在'));
      }else {
        callback();
      }
    },
    checkPassword(rule, value, callback) {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else if (this.loginError === '密码不正确'){
        callback(new Error('密码不正确'));
      }else {
        callback();
      }
    }
  }
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    width="500"
    style="padding: 30px"
  >
    <el-form :model="form" :rules="rules" ref="loginForm">
      <el-form-item label="用户名" label-width="70px" prop="userName">
        <template #label>
          <div>
            <el-icon size="large"><UserFilled /></el-icon>
          </div>
        </template>
        <el-input v-model="form.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码" label-width="70px" prop="password">
        <template #label>
          <div>
            <el-icon size="large"><Lock /></el-icon>
          </div>
        </template>
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div align="center">
        <el-button type="primary" round @click="onSubmit" style="width: 200px">登录</el-button>
      </div>
    </template>
  </el-dialog>
</template>
